package org.flckphoto;


import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

/**
 * Completes save, delete, and send operations on pictures
 */
public class PhotoManager extends Activity{
	public static final String SAVE = "SAVE";
	public static final String DELETE = "DELETE";
	public static final String RESULT = "RESULT";
	public static final String PICTURE = "PICTURE";
	
	private static final String TAG ="PhotoManager";
	private static final int AUTH_REQUEST = 8675309;
	Button save;
	Button delete;
	Button send;
	String dataPath;
	ImageView image;
	byte[] data;
	boolean saved;
	boolean sendBool;
	Bitmap bm;
	ProgressDialog pDia;

	
	@Override
	public void onCreate(Bundle photoManage){
		super.onCreate(photoManage);
		setContentView(R.layout.photomanager);
		image = (ImageView) findViewById(R.id.image);
		
		sendBool = false;
		
		if(photoManage == null) {
			data = getIntent().getByteArrayExtra("image");
			dataPath = getIntent().getStringExtra("path");
			saved = getIntent().getBooleanExtra("saved", false);
		}
		else {
			data = photoManage.getByteArray("image");
			dataPath = photoManage.getString("path");
			saved = photoManage.getBoolean("saved", false);
		}
		
		//create progress dialog
		pDia = new ProgressDialog(PhotoManager.this);
		pDia.setCancelable(false);
		pDia.setMessage("Sending to Flickr...");
		pDia.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		
		save = (Button) findViewById(R.id.save);
		save.setOnClickListener( new OnClickListener(){
			@Override
			public void onClick(View v) {
				Log.d(TAG, "save clicked");
				save();
				Intent bundle = new Intent();
				bundle.putExtra(RESULT, SAVE);
				bundle.putExtra(PICTURE, dataPath);
				setResult(Activity.RESULT_OK, bundle);
				finish();
			}
		});
		
		delete = (Button) findViewById(R.id.delete);
		delete.setOnClickListener( new OnClickListener(){
			@Override
			public void onClick(View v) {
				
				Log.d(TAG, "delete clicked");
				delete();
				Intent bundle = new Intent();
				bundle.putExtra(RESULT, DELETE);
				bundle.putExtra(PICTURE, dataPath);
				setResult(Activity.RESULT_OK, bundle);
				finish();
			}
			
			
		});
		
		send = (Button) findViewById(R.id.send);
		send.setOnClickListener( new OnClickListener(){
			@Override
			public void onClick(View v) {
				Log.d(TAG, "send clicked");
				send();
			}
			
			
		});
		
		if(saved) {
			save.setEnabled(false);
		}
		
		if(data == null) {
			bm = Util.optimizeImage(dataPath);
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			bm.compress(CompressFormat.JPEG, 100, out);
			data = out.toByteArray();
			image.setImageBitmap(bm);
			try {
				out.close();
			}
			catch(IOException e){
				Log.e(TAG, e.getMessage());
			}
		}
		else {
			delete.setText("Discard");
			bm = Util.optimizeImage(data);
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			bm.compress(CompressFormat.JPEG, 100, out);
			data = out.toByteArray();
			image.setImageBitmap(bm);
			try {
				out.close();
			}
			catch(IOException e){
				Log.e(TAG, e.getMessage());
			}
		}
	}
	
	@Override
	public void onSaveInstanceState(Bundle bundle) {
		if(bm != null && !sendBool)
			bm.recycle();
		
		bundle.putByteArray("image", data);
		bundle.putString("path", dataPath);
		bundle.putBoolean("saved", saved);
	}
	

	public void save(){
		Log.d(TAG, "save clicked");
		
		if(!saved) {
			try {
				String flickData = Settings.getDataPath();
				if(!flickData.equals("")) {
					dataPath = flickData + System.currentTimeMillis() + ".jpg";
					File sav = new File(dataPath);
					if(!sav.exists() && sav.createNewFile()) {
						FileOutputStream f = new FileOutputStream(sav);
						f.write(data);
						f.close();
						Toast.makeText(getApplicationContext(), "Picture has been saved.", Toast.LENGTH_SHORT).show();
						saved = true;
						save.setEnabled(false);
					}
				}
			}
			catch(IOException e ) {
				Log.e(TAG, e.getMessage());
			}
		}
	}
	
	/**
	 * Deletes the currently previewed picture
	 */
	public void delete(){
		Log.d(TAG, "delete clicked");
		if(!dataPath.equals("")){
			File del = new File(dataPath);
			if(!del.delete())
				Log.e(TAG, "could not delete file: " + dataPath);
			else
				Toast.makeText(getApplicationContext(), "Picture deleted.", Toast.LENGTH_SHORT).show();
		}
	}
	
	/**
	 * sends the picture to \flickr
	 */
	public void send() {
		Log.d(TAG, "send clicked");
		
		//save the picture
		save();
		
		//check if we are authenticated with flickr
		if(FlickrManager.getSingleton().isAuthenticated()) {
			sendBool = true;
			pDia.show();
			new UploadImageTask().execute(data);
		}
		//if not authenticated then try to authenticate
		else {
			sendBool = true;
			Intent intent = new Intent(this, AuthenticationActivity.class);
			startActivityForResult(intent,AUTH_REQUEST);
		}
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent intData) {
		if(requestCode == AUTH_REQUEST) {
			if(resultCode == Activity.RESULT_OK) {
				pDia.show();
				new UploadImageTask().execute(data);
			}
			else {
				Log.e(TAG, "Cannot send picture, authentication failed!");
			}
		}
	}
	
	private class UploadImageTask extends AsyncTask<byte[], Void, Void> {

		@Override
		protected Void doInBackground(byte[]... params) {
			FlickrManager.getSingleton().sendPicture(params[0]);
			return null;
		}
		
		@Override
		protected void onPostExecute(Void result) {
			pDia.dismiss();
			Intent bundle = new Intent();
			bundle.putExtra(RESULT, SAVE);
			bundle.putExtra(PICTURE, dataPath);
			setResult(Activity.RESULT_OK, bundle);
			finish();
		}
	}

}
